<script setup>
import { ref, computed, watch } from 'vue';
import { useDrag } from '../hooks/useDrag';

const props = defineProps({
  id: { type: String, required: true },
  x: { type: Number, default: 0 },
  y: { type: Number, default: 0 },
  width: { type: Number, default: 100 },
  height: { type: Number, default: 50 },
});

const emit = defineEmits(['delete', 'update:position']);

const localX = ref(props.x);
const localY = ref(props.y);

const { onMouseDown, isDragging } = useDrag({
  x: localX,
  y: localY,
});

watch([localX, localY], ([newX, newY]) => {
  emit('update:position', { id: props.id, x: newX, y: newY, width: props.width, height: props.height });
});

const style = computed(() => ({
  left: `${localX.value}px`,
  top: `${localY.value}px`,
  width: `${props.width}px`,
  height: `${props.height}px`,
}));

/**
 * @description 处理键盘事件以实现无障碍移动
 * @param {KeyboardEvent} event - 键盘事件
 */
function handleKeyDown(event) {
  const step = 10;
  switch (event.key) {
    case 'ArrowUp':
      localY.value -= step;
      break;
    case 'ArrowDown':
      localY.value += step;
      break;
    case 'ArrowLeft':
      localX.value -= step;
      break;
    case 'ArrowRight':
      localX.value += step;
      break;
  }
}
</script>

<template>
  <div
    class="sign-draggable"
    :style="style"
    @mousedown="onMouseDown"
    @keydown="handleKeyDown"
    :tabindex="0"
    :aria-grabbed="isDragging"
  >
    <slot>Sign Here</slot>
    <button @click.stop="emit('delete', id)" class="delete-btn" aria-label="删除签章">X</button>
  </div>
</template>

<style scoped>
.sign-draggable {
  position: absolute;
  border: 1px dashed #333;
  cursor: move;
}
.delete-btn {
  position: absolute;
  top: -10px;
  right: -10px;
  width: 20px;
  height: 20px;
  background: red;
  color: white;
  border-radius: 50%;
  border: none;
  cursor: pointer;
}
</style>